package com.zhou.wx;

import com.alibaba.fastjson.JSON;
import com.zhou.bean.*;
import com.zhou.mvc.ResponseBody;
import com.zhou.service.ExpressService;
import com.zhou.service.FastManService;
import com.zhou.service.UserService;
import com.zhou.utils.DateFormatUtil;
import com.zhou.utils.RandomUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Stream;

public class UserController {
    @ResponseBody("/wx/loginSms.do")
    public String sendSms(HttpServletRequest req, HttpServletResponse resp){
        String phone = req.getParameter("phone");
        String code = RandomUtil.getCode()+"";
        System.out.println("您的验证码为"+code);
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("验证码发送成功");
        req.getSession().setAttribute(phone,code);
        return JSON.toJSONString(msg);
    }
    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        String phone = req.getParameter("phone");
        String code = req.getParameter("code");
        String code1 = (String) req.getSession().getAttribute(phone);
        Message message = new Message();
        if (code1==null){
            //这个手机号未获取短信
            message.setStatus(-1);
            message.setResult("手机号码为获取短信");

        }else if (code.equals(code1)){
            //验证码一致
            if (FastManService.findBySysPhone(phone).getSysPhone()!=null){
                //如果是快递员
                FastMan fastMan = FastManService.findBySysPhone(phone);
                int id = fastMan.getId();
                FastManService.setLoginTime(id);
                message.setStatus(1);
                req.getSession().setAttribute("isUser",1);
                req.getSession().setAttribute("WxUser",FastManService.findBySysPhone(phone));
                req.getSession().setAttribute("phone",phone);
            }else {
                //如果此用户从未登录过自动注册，只有手机号和创建时间，其他信息登录后可进行补全
                if (UserService.findByUserPhone(phone).getUserPhone()==null){
                    User user = new User();
                    user.setUserPhone(phone);
                    user.setCreateTime(DateFormatUtil.format(new Date()));
                    user.setLoginTime(DateFormatUtil.format(new Date()));
                    UserService.addUser(user);
                }
                User user = UserService.findByUserPhone(phone);
                int id = user.getId();
                UserService.setLoginTime(id);
                //用户
                message.setStatus(0);
                req.getSession().setAttribute("isUser",0);
                req.getSession().setAttribute("WxUser",UserService.findByUserPhone(phone));
                req.getSession().setAttribute("phone",phone);
            }

        }else {
            //验证码不一致
            message.setStatus(-2);
            message.setResult("验证码不一致，请检查");
        }
        return JSON.toJSONString(message);

    }
    @ResponseBody("/wx/userInfo.do")
    public String isUser(HttpServletRequest req, HttpServletResponse resp){
        int isUser = (int) req.getSession().getAttribute("isUser");
        Message message = new Message();
        if (isUser==1){
            //快递员
            message.setStatus(1);
            FastMan wxUser = (FastMan) req.getSession().getAttribute("WxUser");
            message.setResult(wxUser.getSysPhone());
        }else {
            //用户
            message.setStatus(0);
            User wxUser = (User) req.getSession().getAttribute("WxUser");
            message.setResult(wxUser.getUserPhone());
        }
        return JSON.toJSONString(message);

    }
    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp){
            //1.销毁session
            req.getSession().invalidate();
            //2.给客户端回复消息
        Message message = new Message(0);
        return JSON.toJSONString(message);
    }
    @ResponseBody("/wx/findExpressByUserPhone.do")
    public String findExpressByUserPhone(HttpServletRequest req, HttpServletResponse resp){
        int isUser = (int) req.getSession().getAttribute("isUser");
        String phone = null;
        if (isUser==1){
            //快递员
            FastMan wxUser = (FastMan) req.getSession().getAttribute("WxUser");
            phone  = wxUser.getSysPhone();
        }else {
            //用户
            User wxUser = (User) req.getSession().getAttribute("WxUser");
            phone = wxUser.getUserPhone();
        }
        List<Express> expressList = ExpressService.findByUserPhone(phone);
        List<nExpress> list1 = new ArrayList<>();
        for (Express express : expressList) {
            String inTime = DateFormatUtil.format(express.getInTime());
            String outTime = express.getOutTime()==null?"未出库":DateFormatUtil.format(express.getOutTime());
            String status = express.getStatus()==0?"未取件":"已取件";
            String code = express.getCode()==null?"已取件":express.getCode();
            nExpress nExpress = new nExpress(express.getId(), express.getNumber(), express.getUsername(), express.getUserPhone(), express.getCompany(), code,inTime,outTime,status,express.getSysPhone());
            list1.add(nExpress);
        }
        Message msg = new Message();
        if (expressList.size()==0){
            msg.setStatus(-1);
        }else {
            msg.setStatus(0);
            //流过滤
            Stream<nExpress> status0Stream = list1.stream().filter(express -> {
                if (express.getStatus().equals("未取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2)->{
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int)(o1Time-o2Time);
            });
            Stream<nExpress> status1Stream = list1.stream().filter(express -> {
                if (express.getStatus().equals("已取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2)->{
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int)(o1Time-o2Time);
            });
            Object[] s0 = status0Stream.toArray();
            Object[] s1 = status1Stream.toArray();
            Map data = new HashMap();
            data.put("status0",s0);
            data.put("status1",s1);
            msg.setData(data);
        }
        return JSON.toJSONString(msg);
    }
    @ResponseBody("/wx/userExpressList.do")
    public String expressList(HttpServletRequest req, HttpServletResponse resp){
        String userPhone = req.getParameter("userPhone");
        List<Express> expressList = ExpressService.findByUserPhone(userPhone);
        List<nExpress> list1 = new ArrayList<>();
        for (Express express : expressList) {
            String inTime = DateFormatUtil.format(express.getInTime());
            String outTime = express.getOutTime()==null?"未出库":DateFormatUtil.format(express.getOutTime());
            String status = express.getStatus()==0?"未取件":"已取件";
            String code = express.getCode()==null?"已取件":express.getCode();
            nExpress nExpress = new nExpress(express.getId(), express.getNumber(), express.getUsername(), express.getUserPhone(), express.getCompany(), code,inTime,outTime,status,express.getSysPhone());
            list1.add(nExpress);
        }
        Message msg = new Message();
        if (expressList.size()==0){
            msg.setStatus(-1);
        }else {
            msg.setStatus(0);
            //流过滤
            Stream<nExpress> status0Stream = list1.stream().filter(express -> {
                if (express.getStatus().equals("未取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2)->{
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int)(o1Time-o2Time);
            });
            Object[] s0 = status0Stream.toArray();
            msg.setData(s0);
        }
        return JSON.toJSONString(msg);
    }
    @ResponseBody("/wx/getUsername.do")
    public String getUsername(HttpServletRequest req, HttpServletResponse resp){
        String phone = (String) req.getSession().getAttribute("phone");
        FastMan fastman = FastManService.findBySysPhone(phone);
        Message message = new Message();
        message.setStatus(0);
        message.setData(fastman);
        return  JSON.toJSONString(message);
    }
    @ResponseBody("/wx/user/update.do")
    public String updateUser(HttpServletRequest req, HttpServletResponse resp){
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        int isUser = (int) req.getSession().getAttribute("isUser");
        int id = 0 ;
        if (isUser==1){
            //快递员
            FastMan wxUser = (FastMan) req.getSession().getAttribute("WxUser");
            wxUser.setUsername(name);
            wxUser.setSysPhone(phone);
            System.out.println(wxUser);
             id = wxUser.getId();
             FastManService.updateFastMan(id,wxUser);
        }else {
            //用户
            User wxUser = (User) req.getSession().getAttribute("WxUser");
            wxUser.setUserPhone(phone);
            wxUser.setUsername(name);
            System.out.println(wxUser);
            id = wxUser.getId();
            UserService.updateUser(id,wxUser);
        }
        Message message = new Message();
        message.setStatus(0);
        message.setResult("修改成功");
        return JSON.toJSONString(message);
    }
}
